package com.tianji.promotion.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.utils.CollUtils;
import com.tianji.promotion.constants.PromotionConstants;
import com.tianji.promotion.entity.po.Coupon;
import com.tianji.promotion.entity.po.ExchangeCode;
import com.tianji.promotion.entity.query.CodeQuery;
import com.tianji.promotion.entity.vo.ExchangeCodeVO;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.tianji.promotion.constants.PromotionConstants.COUPON_RANGE_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author lemon
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 异步生成兑换码
     *
     * @param coupon
     */
    @Transactional
    @Async("generateExchangeCodeExecutor") // 指定线程池
    @Override
    public void asyncGenerateCode(Coupon coupon) {
        log.info("异步生成兑换码  线程池名称：{}", Thread.currentThread().getName());
        // 发放数量
        Integer totalNum = coupon.getTotalNum();
        String key = PromotionConstants.COUPON_CODE_SERIAL_KEY;
        // 1.获取Redis自增序列号
        // 返回的就是加后的值
        Long result = stringRedisTemplate.opsForValue().increment(key, totalNum);
        if (result == null) {
            return;
        }
        int maxSerialNum = result.intValue();
        int begin = result.intValue() - totalNum + 1;
        int end = result.intValue();

        List<ExchangeCode> list = new ArrayList<>();
        // 生成兑换码
        for (int serialNum = begin; serialNum <= end; serialNum++) {
            String code = CodeUtil.generateCode(serialNum, coupon.getId());
            ExchangeCode e = new ExchangeCode();
            e.setCode(code);
            e.setId(serialNum);
            e.setExchangeTargetId(coupon.getId());
            e.setExpiredTime(coupon.getIssueEndTime());
            list.add(e);
        }

        // 批量保存
        this.saveBatch(list);

        // 4.写入Redis缓存，member：couponId，score：兑换码的最大序列号
        stringRedisTemplate.opsForZSet().add(COUPON_RANGE_KEY, coupon.getId().toString(), maxSerialNum);
    }

    /**
     * 分页查询兑换码
     *
     * @param query
     * @return
     */
    @Override
    public PageDTO<ExchangeCodeVO> queryCodePage(CodeQuery query) {
        // 1.分页查询兑换码
        Page<ExchangeCode> page = lambdaQuery()
                .eq(ExchangeCode::getStatus, query.getStatus())
                .eq(ExchangeCode::getExchangeTargetId, query.getCouponId())
                .page(query.toMpPage());
        // 2.返回数据
        List<ExchangeCode> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }
        // po -> vo
        List<ExchangeCodeVO> voList = records.stream().map(item -> {
            ExchangeCodeVO vo = new ExchangeCodeVO();
            vo.setCode(item.getCode());
            vo.setId(item.getId());
            return vo;
        }).collect(Collectors.toList());
        return PageDTO.of(page, voList);
    }

    /**
     * 更新兑换码的状态
     *
     * @param serialNum
     * @param flag
     * @return
     */
    @Override
    public boolean updateExchangeCodeMark(long serialNum, boolean flag) {
        // 修改兑换码 的自增id 对应的offset 的值
        Boolean aBoolean = stringRedisTemplate.opsForValue().setBit(PromotionConstants.COUPON_CODE_MAP_KEY, serialNum, flag);
        return aBoolean != null && aBoolean;
    }

    /**
     * 根据兑换码获取优惠券id
     *
     * @param serialNum
     * @return
     */
    @Override
    public Long exchangeTargetId(long serialNum) {
        // 1.查询score值比当前序列号大的第一个优惠券
        Set<String> results = stringRedisTemplate.opsForZSet().rangeByScore(
                COUPON_RANGE_KEY, serialNum, serialNum + 5000, 0L, 1L);
        if (CollUtils.isEmpty(results)) {
            return null;
        }
        // 2.数据转换  这里得到的是优惠券的id
        String next = results.iterator().next();
        return Long.parseLong(next);
    }
}
